package cn.ujn.medicalbackend.controller;

import cn.ujn.medicalbackend.common.BaseResponse;
import cn.ujn.medicalbackend.common.ErrorCode;
import cn.ujn.medicalbackend.common.ResultUtils;
import cn.ujn.medicalbackend.domain.Sale;
import cn.ujn.medicalbackend.dto.SaleQuery;
import cn.ujn.medicalbackend.exception.BusinessException;
import cn.ujn.medicalbackend.request.*;
import cn.ujn.medicalbackend.service.SaleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/sale")
@CrossOrigin(origins = {"http://localhost:9092"})
public class SaleController {
    @Autowired
    private SaleService saleService;

    @GetMapping("/list/sale")
    public BaseResponse<Page<Sale>> getsaleListByPage(SaleQuery saleQuery) {
        if (saleQuery== null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Sale sale = new Sale();
        BeanUtils.copyProperties(saleQuery, sale);
        QueryWrapper<Sale> queryWrapper = new QueryWrapper<>(sale);
        Page<Sale> page = new Page<>(saleQuery.getPageNum(), saleQuery.getPageSize());
        Page<Sale> tempPage = saleService.page(page, queryWrapper);
        Page<Sale> resultPage = saleService.salePageTransfer(tempPage);
        return ResultUtils.success(resultPage);
    }
    @PostMapping("/add")
    public BaseResponse<Long> addSale(@RequestBody SaleAddRequest saleAddRequest, HttpServletRequest request) {
        if (saleAddRequest== null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        long saleId =saleService.addSale(saleAddRequest, request);
        return ResultUtils.success(saleId);
    }

    @PostMapping("/update")
    private BaseResponse<Boolean> updateSale(@RequestBody SaleUpdateRequest saleUpdateRequest, HttpServletRequest request) {

        if (saleUpdateRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        boolean result = saleService.updateSale(saleUpdateRequest,request);
        return ResultUtils.success(true);
    }

    @PostMapping("/delete")
    private BaseResponse<Boolean> deleteSale(@RequestBody SaleDeleteRequest saleDeleteRequest, HttpServletRequest request) {
        if (saleDeleteRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result =  saleService.deleteSale(saleDeleteRequest, request);
        return ResultUtils.success(result);
    }
}
